package com.rocketmq.demo;

import com.rocketmq.constants.MqConstants;
import com.rocketmq.domain.MsgModel;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName FOrderLyTest
 * @Description 顺序消息
 * @Author Patrick Star
 * @Date 2025/7/27 18:55
 */
public class FOrderLyTest {

    private List<MsgModel> orders = Arrays.asList(
            new MsgModel("T_0001" ,1,"下单"),
            new MsgModel("T_0001" ,1,"短信"),
            new MsgModel("T_0001" ,1,"物流"),

            new MsgModel("T_0002" ,2,"下单"),
            new MsgModel("T_0002" ,2,"短信"),
            new MsgModel("T_0002" ,2,"物流")
    );

    @Test
    public void orderlyProducer() throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("orderly-producer-group");
        producer.setNamesrvAddr(MqConstants.NAMESERVER_ADDR);
        producer.start();

        // 发送顺序消息 发送时要确保有序 并且要发到同一个队列里面去
        orders.forEach(msgModel -> {
            Message message = new Message("orderlyTopic", msgModel.toString().getBytes());
            try {
                // 相同的订单号 按照顺序去相同的队列中去
                producer.send(message, (list, message1, arg) -> {
                    // 在这里选择队列
                    // 这里的arg就是send方法的第三个参数 也就是这里的订单号
                    int hashCode = arg.toString().hashCode();
                    int index = Math.abs(hashCode) % list.size();
                    return list.get(index);
                }, msgModel.getOrderSn());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        producer.shutdown();
        System.out.println("发送完毕");
    }

    @Test
    public void orderlyConsumer() throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("orderly-consumer-group");
        consumer.setNamesrvAddr(MqConstants.NAMESERVER_ADDR);
        consumer.subscribe("orderlyTopic", "*");
        // MessageListenerConcurrently 默认是多线程并发模式 重试16次 如果1616次都失败 会将这个消息放到其他队列里面去
        // 使用MessageListenerOrderly 确保消费者单线程消费 这中会无限重试Integer.MAX_VALUE次
        consumer.registerMessageListener(new MessageListenerOrderly() {
            // 是每一个队列一个线程
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                System.out.println("线程id: " + Thread.currentThread().getId());
                System.out.println("收到的消息为" + new String(list.get(0).getBody()));
                // SUSPEND_CURRENT_QUEUE_A_MOMENT 这个状态会出现异常重试
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();
        System.in.read();
    }
}
